﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public partial class qlcongviec : System.Web.UI.Page
{
    VLGDataContext _db7 = new VLGDataContext();
    CommonPage cm4 = new CommonPage();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                if (String.IsNullOrEmpty(Session["KhachHang"].ToString()))
                {
                    Response.Redirect(ResolveClientUrl("accessDenied.aspx"));
                }
                else
                {
                    this.LoadDataDrop();
                    this.showEdit();
                }
            }
            catch {}
        }
    }
    void showEdit()
    {
        string opt= Request.QueryString["op"];
        if (opt == "add")
        {
            this.LoadDataDrop();
            Page.Title="Trang cá nhân | Thêm một công việc mới";
            try
            {
                string ten = Request.QueryString["to"];
                if (String.IsNullOrEmpty(ten) == false)
                {
                    txtTenCVS.Text = ten;
                }
                RequiredFieldValidator1.Visible = true;
                FileUpload1.Visible = true;
            }
            catch
            {
                txtTenCVS.Text = "";
                RequiredFieldValidator1.Visible = true;
                FileUpload1.Visible = true;
            }
        }
        else if (opt == "edit")
        {
            Page.Title = "Trang cá nhân | Chỉnh sửa công việc mới";
            string idGig = Request.QueryString["gc"];
            if (String.IsNullOrEmpty(idGig))
            {
                Response.Redirect(ResolveClientUrl("~/accessDenied.aspx"));
            }
            else
            {
                try
                {
                    Gig gigEdit = _db7.Gigs.Single(idedit => idedit.idGig == int.Parse(idGig) && idedit.idAcc == cm4.Customer.idAcc);
                    //xuat du lieu ra
                    FileUpload1.Visible = false;
                    FileUpload4.Visible = true;
                    btnLuu.Visible = false;
                    btn_capNhat.Visible = true;
                    anhdaidien.Style.Add("display", "block");
                    txtTenCVS.Text = gigEdit.TenCongViec;
                    txtMota.Text = gigEdit.MoTaCV;
                    txtTags.Text = gigEdit.Tags;
                    txtTuGTU.Text = gigEdit.TuGioiThieu;
                    txtNgayHTCV.Text = gigEdit.SoNgayCanDeXong.ToString();
                    DropDownList1.SelectedValue = gigEdit.idCategory.ToString();
                    Image1.ImageUrl = ResolveClientUrl("~/upload/" + gigEdit.UrlHinh1);
                    //CheckBox1.Checked = (bool)gigEdit.AnHien;
                }
                catch
                {
                    Response.Redirect(ResolveClientUrl("~/accessDenied.aspx"));
                }
            }
        }
        else
        {
            Response.Redirect(ResolveClientUrl("~/accessDenied.aspx"));
        }
    }
    void LoadDataDrop()
    {
        var itemDrop = from dmn in _db7.Categories
                       where dmn.AnHien == true
                       select dmn;
        DropDownList1.DataSource = itemDrop;
        DropDownList1.DataTextField = "TenCate";
        DropDownList1.DataValueField = "idCategory";
        DropDownList1.DataBind();
    }
    protected void btnLuu_Click(object sender, EventArgs e)
    {
        //if (RangeValidator1.IsValid)
        //{
            // lay gia tri
            string tenCV = txtTenCVS.Text.Trim();
            string tenCVKD = AllCode.Utils.ConvertToUnSign(tenCV);
            string moTaCV = txtMota.Text.Trim();
            string gioiThieu = txtTuGTU.Text.Trim();
            string tags = txtTags.Text.Trim();
            int songay = int.Parse(txtNgayHTCV.Text.Trim().ToString());
            // check file upload
            if (FileUpload1.HasFile)
            {
                //Response.Write(FileUpload1.PostedFile.ContentType.ToString());
                //return;
                if (!FileUpload1.PostedFile.ContentType.Equals("image/jpeg"))
                {
                    lblLoi.Text = "Chỉ đăng ảnh dạng JPEG.";
                    return;
                }
                else if (FileUpload1.PostedFile.ContentLength > 1048576)
                {
                    lblLoi.Text = "Kích thước ảnh quá lớn. Kích thước ảnh phải bé hơn 1 MB";
                    return;
                }
                else
                {
                    string[] arrayfilename = Path.GetFileName(FileUpload1.FileName).Split('.');
                    string ten = arrayfilename[0];
                    string duoi = arrayfilename[1];
                    string filename = ten + DateTime.Today.Ticks.ToString() + "." + duoi;

                    //string filename2 = Path.GetFileName(FileUpload2.FileName);
                    //string filename3 = Path.GetFileName(FileUpload3.FileName);
                    try
                    {
                        Gig gigC = new Gig
                        {
                            TenCongViec = tenCV,
                            MoTaCV = moTaCV,
                            TuGioiThieu = gioiThieu,
                            UrlHinh1 = filename,
                            Tags = tags,
                            SoNgayCanDeXong = songay,
                            idAcc = cm4.Customer.idAcc,
                            idCategory = int.Parse(DropDownList1.SelectedValue),
                            GiaTien = 5,
                            NgayTao = DateTime.Now,
                            SoLuotThich = 0,
                            SoLuotKoThich = 0,
                            Duyet = false,
                            TenCongViec_KD = tenCVKD,
                            TrangThai = 0,
                            LinkVideo=""
                            //UrlHinh2=filename2,
                            //UrlHinh3=filename3
                        };
                        _db7.Gigs.InsertOnSubmit(gigC);
                        _db7.SubmitChanges();
                        try
                        {
                            //FileUpload1.SaveAs(Server.MapPath(("upload/")) + filename);
                            thunhoVaLuu2(270, 210, FileUpload1, filename);
                            bool kqup = thunhoVaLuu(50, 40, FileUpload1, filename);
                            if (kqup == true)
                            {
                                Response.Redirect(ResolveClientUrl("~/yourPage.aspx"));
                            }
                            else
                            {
                                lblLoi.Text = "Không thể tạo thumnail";
                            }
                        }
                        catch (Exception cc)
                        {
                            lblLoi.Text = "Trùng tên rồi" + cc.Message;
                            return;
                        }
                    }
                    catch (Exception cca)
                    {
                        lblLoi.Text = "Có lỗi trong quá trình thêm mới" + cca.Message;
                        return;
                    }

                }
            }
            // them du lieu vao
        //}
        //else
        //{
        //    return;
        //}
    }
    public bool thunhoVaLuu(int chieuRong, int chieuCao, FileUpload fulPhoto2,string tenfileThum)
    {
        bool flag = false;
        string pathAvatars = Server.MapPath(("upload/thumnails/"));
        try
        {
            int thumbWidth = chieuRong;
            int thumbHeight = chieuCao;
            
            System.Drawing.Image oImg = System.Drawing.Image.FromStream(fulPhoto2.PostedFile.InputStream);
            System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);

            Graphics oGraphic = Graphics.FromImage(oThumbNail);
            oGraphic.CompositingQuality = CompositingQuality.HighQuality;
            oGraphic.SmoothingMode = SmoothingMode.HighQuality;
            oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

            Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
            oGraphic.DrawImage(oImg, oRectangle);

            oThumbNail.Save(pathAvatars + tenfileThum, ImageFormat.Jpeg);
            oImg.Dispose();
            flag = true;
            return flag;
        }
        catch (Exception ex)
        {
            return flag;
        }
    }
    public bool thunhoVaLuu2(int chieuRong, int chieuCao, FileUpload fulPhoto2, string tenfileThum)
    {
        bool flag = false;
        string pathAvatars = Server.MapPath(("upload/"));
        try
        {
            int thumbWidth = chieuRong;
            int thumbHeight = chieuCao;

            System.Drawing.Image oImg = System.Drawing.Image.FromStream(fulPhoto2.PostedFile.InputStream);
            System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);

            Graphics oGraphic = Graphics.FromImage(oThumbNail);
            oGraphic.CompositingQuality = CompositingQuality.HighQuality;
            oGraphic.SmoothingMode = SmoothingMode.HighQuality;
            oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

            Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
            oGraphic.DrawImage(oImg, oRectangle);

            oThumbNail.Save(pathAvatars + tenfileThum, ImageFormat.Jpeg);
            oImg.Dispose();
            flag = true;
            return flag;
        }
        catch (Exception ex)
        {
            return flag;
        }
    }
    protected void btn_capNhat_Click(object sender, EventArgs e)
    {
        // lay gia tri
        string tenCV2 = txtTenCVS.Text.Trim();
        //string tenCVKD2 = AllCode.Utils.ConvertToUnSign(tenCV2);
        string moTaCV2 = txtMota.Text.Trim();
        string gioiThieu2 = txtTuGTU.Text.Trim();
        string tags2 = txtTags.Text.Trim();
        int songay2 = int.Parse(txtNgayHTCV.Text.Trim().ToString());

        string idGigRQ = Request.QueryString["gc"];
        //Literal1.Text = "<script type=\"text/javascript\">alert('"+tenCV2+"')</script>";
        
        //// check file upload
        if (FileUpload4.HasFile)
        {
            if (!FileUpload4.PostedFile.ContentType.Equals("image/jpeg"))
            {
                lblLoi.Text = "Chỉ đăng ảnh dạng JPEG.";
                return;
            }
            else if (FileUpload4.PostedFile.ContentLength > 1048576)
            {
                lblLoi.Text = "Kích thước ảnh quá lớn. Kích thước ảnh phải bé hơn 1 MB";
                return;
            }
            else
            {
                string[] arrayfilename = Path.GetFileName(FileUpload4.FileName).Split('.');
                string ten = arrayfilename[0];
                string duoi = arrayfilename[1];
                string filename22 = ten + DateTime.Today.Ticks.ToString() + "." + duoi;
                try
                {
                    Gig gigC2 = _db7.Gigs.Single(ited => ited.idGig == int.Parse(idGigRQ));
                    gigC2.TenCongViec = tenCV2;
                    gigC2.TenCongViec_KD = AllCode.Utils.ConvertToUnSign(tenCV2);
                    gigC2.MoTaCV = moTaCV2;
                    gigC2.TuGioiThieu = gioiThieu2;
                    gigC2.Tags = tags2;
                    gigC2.SoNgayCanDeXong = songay2;
                    gigC2.idCategory = int.Parse(DropDownList1.SelectedValue.ToString());
                    //gigC2.AnHien = CheckBox1.Checked;
                    string tenhinhtemp = gigC2.UrlHinh1;
                    try
                    {
                        //FileUpload4.SaveAs(Server.MapPath("~/upload/") + filename22);
                        thunhoVaLuu2(270, 210, FileUpload4, filename22);
                        bool kqup = thunhoVaLuu(50, 40, FileUpload4, filename22);
                        tenhinhtemp = filename22;
                    }
                    catch
                    {
                        lblLoi.Text = "Có lỗi trong qua trình cập nhật hình";
                        return;
                    }
                    gigC2.UrlHinh1 = filename22;
                    // cap nhat
                    _db7.SubmitChanges();
                    Response.Redirect(ResolveClientUrl("~/yourPage.aspx"));
                }
                catch
                {
                    lblLoi.Text = "Có lỗi trong quá trình cập nhật";
                    return;
                }

            }
        }
        else
        {
            try
            {
                Gig gigC22 = _db7.Gigs.Single(ited => ited.idGig == int.Parse(idGigRQ));
                gigC22.TenCongViec = tenCV2;
                gigC22.TenCongViec_KD = AllCode.Utils.ConvertToUnSign(tenCV2);
                gigC22.MoTaCV = moTaCV2;
                gigC22.TuGioiThieu = gioiThieu2;
                gigC22.Tags = tags2;
                gigC22.SoNgayCanDeXong = songay2;
                gigC22.idCategory = int.Parse(DropDownList1.SelectedValue.ToString());
                //gigC22.AnHien = CheckBox1.Checked;
                // cap nhat
                _db7.SubmitChanges();
                Response.Redirect(ResolveClientUrl("~/yourPage.aspx"));

            }
            catch
            {
                lblLoi.Text = "Có lỗi trong quá trình cập nhật 2";
                return;
            }
        }
    }
}
